package parking_record

import (
	"fmt"
	"parking-lot-go-admin/model"
	"parking-lot-go-admin/model/order"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/tealeg/xlsx/v3"
)

func Download(c *gin.Context) {

	requestDataStruct := struct {
		OutTime []string `json:"out_time"`
	}{}

	c.ShouldBindJSON(&requestDataStruct)

	operators := map[int]string{1: "小强", 2: "泊安飞"}
	parks := map[string]string{
		"110101300023": "北京站停车场（地下）",
		"110106300134": "P1北京南站立体停车场",
		"110106300191": "丰台站站前P2停车场",
	}

	file := xlsx.NewFile()

	for opKey, opName := range operators {
		for parkKey, parkName := range parks {
			sheetName := fmt.Sprintf("%s-%s", opName, parkName)
			sheet, err := file.AddSheet(sheetName)
			if err != nil {
				fmt.Println("Error adding sheet:", err)
				continue
			}

			// 设置表头
			row := sheet.AddRow()
			row.WriteSlice(&[]string{"序号", "车牌号码", "实际停车时间", "实际取车时间", "停车天数", "停车小时", "停车分钟"}, -1)

			//查询信息
			var orderStruct order.OrderStruct
			var orderData []order.OrderStruct
			model.GetModelData(
				model.Db,
				orderStruct.TableName(),
				&orderData,
				model.QueryOptions{
					Conditions: map[string]interface{}{
						"out_time >= ? ":       requestDataStruct.OutTime[0] + " 00:00:00",
						"out_time <= ? ":       requestDataStruct.OutTime[1] + "  23:59:59",
						"status = ?":           2,
						"order_type = ?":       opKey,
						"static_park_code = ?": parkKey,
					},
					Debug: true,
				},
			)
			for index, order := range orderData {
				interval := order.OutTime.Sub(order.InTime)
				days := int(interval.Hours()) / 24
				hours := int(interval.Hours()) % 24
				minutes := int(interval.Minutes()) % 60

				row := sheet.AddRow()
				row.WriteSlice(&[]interface{}{index + 1, order.CarNumber, order.InTime, order.OutTime, days, hours, minutes}, -1)
			}
		}
	}

	// 设置HTTP头部信息
	fileName := fmt.Sprintf("停车记录导出-%d.xlsx", time.Now().Unix())
	c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
	c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", fileName))
	c.Header("Cache-Control", "max-age=0")

	// 保存文件到浏览器输出
	if err := file.Write(c.Writer); err != nil {
		return
	}

	// file.Save("./example.xlsx") // 指定完整路径

}
